{% extends "base.html" %}
{% load cctags %}
{% load ccfilters %}

{% block css %}
<link type="text/css" rel="stylesheet" href="/static/styles/jqueryui/themes/ui-lightness/jquery.ui.all.css"/>
<link type="text/css" rel="stylesheet" href="/static/styles/routes.css"/>
{% endblock %}

{% block scripts %}
{% if site_settings.development %}
    <script type="text/javascript" src="/static/js/jqueryui/jquery-ui-1.8.13.custom.min.js"></script>
{% else %}
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.13/jquery-ui.min.js"></script>
{% endif %}
<script type="text/javascript" src="/static/js/jqueryui/jquery-ui-timepicker-addon.js"></script>
<script type="text/javascript" src="/static/js/jqueryui/i18n/jquery.ui.datepicker-zh-CN.js"></script>
<script type="text/javascript" src="/static/js/jquery.blockUI.js"></script>
<script type="text/javascript" src="/static/js/json2.js"></script>
<script type="text/javascript" src="/static/js/vanadium-min.js"></script>
<script type="text/javascript" src="{% url views.localjavascript 'magicycle.js' %}"></script>
<script type="text/javascript">
var KM2MILE = 0.621371192;
$(document).ready(function(){

    $("#weathers").selectable({
        stop: function() {
				var result = []
				$( ".ui-selected", this ).each(function() {
					var w = $(this).attr("id");
					result.push(w);
				});
                $("#weather").val(result.join(','));
			}
    });

    var efforts = [ '{% _ "n/a" %}', '{% _ "easiest" %}', '{% _ "easy" %}',
                    '{% _ "normal" %}', '{% _ "hard" %}', '{% _ "hardest" %}', '{% _ "HARDESTEST" %}'];
    $("#effort_slider").slider({
            value:0,
			min: 0,
			max: 6,
			step: 1,
            range: "min",
			slide: function( event, ui ) {
				$("#effort_select").html(efforts[ui.value]);
                $("#effort").val(ui.value);
			}
    });

    $.datepicker.setDefaults($.datepicker.regional['{{ lang }}']);
    $.extend($.timepicker._defaults, $.timepicker.regional['{{ lang }}']);

    var loadmore = $("#loadmore");
    var dbcursor = $("#dbcursor");
    var select_route = $("#select_route");
    var routes_loading = $("#routes_loading");
    var route_panel = $("#logride_route .route_panel");
    var select_bike = $("#select_bike");
    var ridename = $("#ridename");
    var starttime = $("#starttime");
    var endtime = $("#endtime");
    var time_duration = $("#time_duration");

    select_route.change(function(){
        var routeid = select_route.val();
        if(routeid != '0'){
            get_route(routeid);
        }
    });

    loadmore.click(function(){
        routes_loading.show();
        load_more_routes();
    });

    starttime.datetimepicker({
        dateFormat: 'yy-mm-dd',
        timeFormat: 'hh:mm',
        onClose: function(dateText, inst) {
            _check_start_end_time(starttime);
            _start_date = starttime.val().split(' ',1);
            _name_this_ride();
        }
    });
    endtime.datetimepicker({
        dateFormat: 'yy-mm-dd',
        timeFormat: 'hh:mm',
        onClose: function(dateText, inst) {
             _check_start_end_time(endtime);
        }
    });
    _get_utc_string = function(dt){
        var utc_string = dt.getUTCFullYear() + '-' + (dt.getUTCMonth()+1) + '-' + dt.getUTCDate() +
                ' ' + dt.getUTCHours() + ':' + dt.getUTCMinutes();
        return utc_string;
    }
    _check_start_end_time = function(timepicker){
        var start = starttime.datetimepicker('getDate');
        var end = endtime.datetimepicker('getDate');
        var now = new Date();
        if(end>now || start>now){
            alert("{% _ 'r u from the future?' %}"+' :)');
            return timepicker.datetimepicker('setDate',null);
        }
        if((end && start) && end<start){
            alert("{% _ 'End can not be less than Start' %}");
            return timepicker.datetimepicker('setDate',null);
        }
        if(end && start){
            $("#time_duration").val(((end-start)/1000/3600).toFixed(1));
        }
        start && $("#starttime_utc").val(_get_utc_string(start));
        end && $("#endtime_utc").val(_get_utc_string(end));
    };
    end_minus_start_hours = function(){
        var start = starttime.datetimepicker('getDate');
        var end = endtime.datetimepicker('getDate');
        if(end && start){
            return ((end-start)/1000/3600).toFixed(1);
        }
        return 0;
    }

    var _route_name = "{{ route.name }}";
    var _start_date = "";
    _name_this_ride = function(){
        ridename.val('['+ _start_date + '] ' + _route_name);
    }


    function get_route(routeid){
       $.post("{% url apis.apisviews.rest %}",
                {method:"get_route_by_id",
                      routeid: routeid
                },
                function(data){
                    data = JSON.parse(data);
                    if (data.status=="ok") {
                        show_route(data.route);
                        _route_name = data.route.name;
                        _name_this_ride();
                        enable_submit();
                    } else {
                        alert(data.message);
                        disable_submit();
                    }
                }
       );
    };

    function show_route(route){
        route_panel.hide();
        $(".preview_map a",route_panel).attr("href", "{% url routes.routesviews.showallroutes%}"+ route.id);
        $(".preview_img",route_panel).attr("src", route.preview_url);
        $(".preview_img",route_panel).attr("title", route.name);

        $(".value",route_panel).html(calc_distance(route.distance));
        $(".route_name a",route_panel).attr("href", "{% url routes.routesviews.showallroutes%}"+ route.id);
        $(".route_name a",route_panel).html(route.name);

        $(".creator",route_panel).html('{% _ "By" %}'+' <a></a> '+'{% _ "Created on" %}'+
                formatutc(route.create_datetime,'yyyy-MM-dd'));
        $(".creator a",route_panel).attr("href", "{% url riders.ridersviews.ridersindex%}"+route.creator_uid);
        $(".creator a",route_panel).attr("title", route.creator);
        $(".creator a",route_panel).html(route.creator);

        $(".route_location",route_panel).html(route.start_address +'</br>  {% _ "to" %}  '+ route.end_address);
        route_panel.fadeIn(1000);

    };

    function load_more_routes(){
        var cur_dbcursor = dbcursor.val();
        $.post("{% url apis.apisviews.rest %}",
                {method:"get_routes_by_uid",
                    uid: '{{ user.uid }}',
                    pagesize: 20,
                    start_cursor: cur_dbcursor,
                    order: "-create_datetime"
                },
                function(data){
                    routes_loading.hide();
                    data = JSON.parse(data);
                    if (data.status=="ok") {
                        dbcursor.val(data.end_cursor);
                        var count = data.routes.length;
                        if(count==0){
                            loadmore.hide();
                        }else{
                            for(var i=0; i<count; i++){
                                insert_route_to_list(data.routes[i]);
                            }
                        }
                    } else {
                        alert(data.message);
                    }
                }
        );
    };

    function insert_route_to_list(route){
        $("option[value='"+route.id+"']", select_route).remove();
        var route_option = $('<option></option>');
        route_option.val(route.id);
        route_option.html('{% _ "My Route" %}: '+route.name+ ' '
                + calc_distance(route.distance) + ' {{ unit.km_mile }}');
        select_route.append(route_option);
    };

    function calc_distance(distance){
        {% ifequal unit.unit "metric" %}
            var new_distance = (distance/1000.0).toFixed(0);
        {% else %}
            var new_distance = (distance/1000.0*KM2MILE).toFixed(0);
        {% endifequal %}
        return new_distance;
    };

    var btn_save = $("#save");
    function disable_submit(){
        btn_save.addClass("disabled");
        btn_save.attr("disabled", true);
    }
    function enable_submit(){
        btn_save.removeClass("disabled");
        btn_save.attr("disabled", false);
    }
    btn_save.click(function(){
        try{
            var routeid = select_route.val();
            var bikeid = select_bike.val();
            if(routeid == "0" || bikeid == "0"){
                alert('{% _ "Please choose route and bike" %}');
                return false;
            }
            var duration = Number(time_duration.val());
            if(duration > end_minus_start_hours()){
                alert('{% _ "Duration can not be greater than end-start" %}');
                return false;
            }

            var notes = $.trim(editor.document.getBody().getText());
            if(notes.length <= 0){
                return confirm('{% _ "r u sure submit without notes" %}?')
            }
        }
        catch(error){
            alert(error);
            return false;
        }
    });
    {% if not route %}
    disable_submit();
    {% endif %}
});
</script>
{% endblock %}

{% block menu %}
{% include '_menu_rides.html' %}
{% endblock %}

{% block main-page %}
<div id="logride">
    <h1 class="group_title">{% _ "Log Ride" %}</h1>
    {% if message %}<h1 class="tips">{{ message|escape }}</h1>{% endif %}
    <form action="" method="post">
        <div class="steps">
            <div class="step_icon"><img class="step" alt="Step one" src="/static/images/step1.png"></div>
            <div class="step_content">
                <div class="step_list"><span class="item_title">{% _ "Choose A Route" %}</span>
                    <select id="select_route" name="select_route" class=":required">
                        {% if route %}
                        <option value="{{ route.id }}">{{ route.name }}
                            {{ route.distance|divide:"1000"|_u|floatformat:"0" }} {{ unit.km_mile }}</option>
                        {% else %}
                            <option value="0"></option>
                            {% for route in user.LatestRoutes %}
                                <option value="{{ route.id }}">{% _ "My Route" %}: {{ route.name }} |
                                    {{ route.distance|divide:"1000"|_u|floatformat:"0" }} {{ unit.km_mile }}</option>
                            {% endfor %}
                            {% for route in user.Favorites %}
                                <option value="{{ route.id }}">{% _ "My Favorite" %}: {{ route.name }} |
                                    {{ route.distance|divide:"1000"|_u|floatformat:"0" }} {{ unit.km_mile }}</option>
                            {% endfor %}
                        {% endif %}
                    </select>
                    <input type="hidden" value="" id="dbcursor"/>
                    <span id="routes_loading" class="hide">
                        <img src="/static/images/loading.gif" alt="{% _ 'route loadig...' %}"/>
                    </span>
                    <a id="loadmore" href="javascript:;"> {% _ "More Routes..." %}</a>
                </div>
                <div class="step_list" id="logride_route">
                    {% include '_route_panel.html' %}
                </div>
                <div class="clear"></div>
                <div class="step_list"><span class="item_title">{% _ "Choose A Bike" %}</span>
                    <select id="select_bike" name="select_bike" class=":required">
                        <option value="0"> </option>
                        {% for bike in user.Bikes %}
                        <option value="{{ bike.id }}">{% _ bike.type %}: {{ bike.name }}</option>
                        {% endfor %}
                    </select>
                    <a id="add_a_bike" href="{% url riders.ridersviews.userpage user.uid %}"> {% _ "Add a bike" %}</a>
                </div>
            </div>
            <div class="clear"></div>
        </div>
        <div class="steps">
            <div class="step_icon"><img class="step" alt="Step two" src="/static/images/step2.png"></div>
            <div class="step_content">
                <div  class="step_list">
                    <span class="item_title">{% _ "Name this Ride" %}</span>
                    <input type="text" id="ridename" name="ridename" size="50"
                               title="Ride Name" class=":max_length|30"/>
                </div>
                <div  class="step_list">
                    <span id="starttime_p">
                        <span class="item_title">{% _ "Start DateTime" %}</span>
                        <input type="text" id="starttime" name="starttime" size="14"
                               title="Start Time" class=":required"/>
                        <input type="hidden" id="starttime_utc" name="starttime_utc"/>
                    </span>
                    <span id="endtime_p">
                        <span class="item_title">{% _ "End DateTime" %}</span>
                        <input type="text" id="endtime" name="endtime" size="14"
                               title="End Time" class=":required"/>
                        <input type="hidden" id="endtime_utc" name="endtime_utc"/>
                    </span>
                    <span> {% _ "Duration" %}
                        <input id="time_duration" name="time_duration" type="text" size="6"
                               title="Duration" class=":float :required"/>
                        {% _ "hours" %}  {% _ "on bike" %} </span>
                </div>
                <div  class="step_list">
                    <span class="item_title weather_title">{% _ "Weather" %}</span>
                    <ul id="weathers">
                        <li class="weather" id="sunny" title="{% _ 'Sunny' %}">
                        </li>
                        <li class="weather" id="sunny_interval" title="{% _ 'Sunny Interval' %}">
                        </li>
                        <li class="weather" id="cloudy" title="{% _ 'Cloudy' %}">
                        </li>
                        <li class="weather" id="overcast" title="{% _ 'Overcast' %}">
                        </li>
                        <li class="weather" id="light_rain" title="{% _ 'Light Rain' %}">
                        </li>
                        <li class="weather" id="rain" title="{% _ 'Rain' %}">
                        </li>
                        <li class="weather" id="thunderstorms" title="{% _ 'Thunderstorms' %}">
                        </li>
                        <li class="weather" id="snow" title="{% _ 'Snow' %}">
                        </li>
                        <input type="hidden" id="weather" name="weather" value=""/>
                    </ul>
                </div>
                <div  class="step_list">
                    <span class="item_title weather_title">{% _ "Effort" %}</span>
                    <div id="effort_slider"></div><div id="effort_select"></div>
                    <input type="hidden" id="effort" name="effort" value="0"/>
                </div>
            </div>
            <div class="clear"></div>
        </div>
        <div class="steps">
            <div class="step_icon"><img class="step" alt="Step three" src="/static/images/step3.png"></div>
            <div class="step_content">
                <div class="step_list">
                    <span class="item_title">{% _ "Notes" %}</span>
                </div>
                <div id="note" class="step_list item_title">
                    <textarea rows="8" cols="80" id="notes" name="notes"></textarea>
                </div>
                <input id="save" type="submit" class=":submit yellowbutton bigsize" value="{% _ "Save" %}"/>
            </div>
            <div class="clear"></div>
        </div>
    </form>
</div>
<script type="text/javascript" src="/static/js/ckeditor/ckeditor.js"></script>
<script>
    var editor;
    CKEDITOR.config.language = "{{ lang }}";
    CKEDITOR.config.filebrowserImageUploadUrl ='{{site_settings.depot_site}}/ckupload/';
    function createEditor() {
        if ( editor )
            editor.destroy();
        editor = CKEDITOR.replace( 'notes', {
            removePlugins : 'elementspath'
        });
    }
    createEditor();

    addUploadButton();
    function addUploadButton(){
        CKEDITOR.on('dialogDefinition', function( ev ){
            var dialogName = ev.data.name;
            var dialogDefinition = ev.data.definition;
            if ( dialogName == 'image' ){
                var infoTab = dialogDefinition.getContents( 'info' );
                infoTab.add({
                    type : 'button',
                    id : 'upload_image',
                    label : '{% _ "Upload Image" %}',
                    onClick : function( evt ){
                       var thisDialog = this.getDialog();
                       var txtUrlObj = thisDialog.getContentElement('info', 'txtUrl');
                       var txtUrlId = txtUrlObj.getInputElement().$.id;
                       addUploadImage(txtUrlId);
                   }
                }, 'browse'); //place front of the browser button
            }
        });
    }
    function addUploadImage(theURLElementId){
        var uploadUrl = "{% url views.upload %}";
        var imgUrl = window.showModalDialog(uploadUrl,"","dialogWidth=220px;dialogHeight=120px;status=yes;");
        if(!imgUrl){
            return;
        }
        var urlObj = document.getElementById(theURLElementId);
        urlObj.value = imgUrl;
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent('change',true,true);
        try{
            urlObj.dispatchEvent(evt);
        }catch(err){
            urlObj.fireEvent("onchange");
        }
    }
</script>
{% endblock %}
